﻿using EStart.DataBase.Event.Domian;
using EStart.DataBase.Event.Domian.EntityEnum;
using EStart.Infrastructure;
using EStart.Infrastructure.Domain;
using EStart.Interface;
using Microsoft.EntityFrameworkCore;
using QuickApp.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EStart.DataBase.EF
{
    public class ServiceCore<T> : IServiceCore<T> where T : EntityCore
    {


        protected readonly DbSet<T> _entities;
        protected readonly UnitOfWork _unitofwork;
        public ServiceCore(DbContext context, EventDbContext eventContext = null)
        {
            _unitofwork = new UnitOfWork();
            if (eventContext != null)
            {
                _unitofwork.eventDbContext = eventContext;
            }
            _entities = context.Set<T>();
            _unitofwork.dbContext = context;

        }


        public void DeleteForge(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            entity.IsDelete = true;
            entity.LastChangeTime = DateTime.Now;
            _unitofwork.RegisterDirty(entity);
        }


        public IQueryable<T> Query(bool isFilter = true)
        {
            return isFilter ? _entities.AsTracking().Where(p => !p.IsDelete) : _entities.AsTracking();
        }

        public void DeleteForge(Expression<Func<T, bool>> express)
        {
            var entity = Query(false).Where(express).FirstOrDefault();
            if (entity != null)
                DeleteForge(entity);

        }

    }
}
